package com.rss.provider.server;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.rss.provider.NewsSubject;
import com.rss.provider.constant.NavigationConstant;
import com.rss.provider.constant.ProviderConstant;
import com.rss.provider.gmail.email.service.GmailEmailSpringService;
import com.rss.provider.service.RssService;
import com.rss.provider.spring.form.SubscriberForm;
import com.rss.provider.spring.form.UpdateForm;
import com.rss.provider.util.DateUtils;

@Controller
@RequestMapping("/dailySports")
public class DailySportsController implements NewsSubject {

	@Autowired
	@Qualifier("RssServiceImpl")
	private RssService rssService;

	@Autowired
	@Qualifier("GmailEmailSpringService")
	private GmailEmailSpringService emailSpringService;

	// this page is called when we are displaying our initial registration form
	@RequestMapping(value = "sendUpdate.htm", method = RequestMethod.GET)
	public String sendUpdatePage() {
		return NavigationConstant.SENDUPDATE;
	}

	@Override
	@RequestMapping(value = "addSubscriber.htm", method = RequestMethod.POST)
	public String subscribe(SubscriberForm subscriberForm) {
		subscriberForm.setSubscribedTo(ProviderConstant.DAILYSPORTS);
		String result = rssService.addSubscriber(subscriberForm);
		if (result.equals("success"))
			return NavigationConstant.SUCCESS;
		return NavigationConstant.FAILED;
	}

	@Override
	@RequestMapping(value = "removeSubscriber.htm", method = RequestMethod.POST)
	public String unSubscribe(SubscriberForm unsubscriberForm) {
		unsubscriberForm.setSubscribedTo(ProviderConstant.DAILYSPORTS);
		String result = rssService.removeSubscriber(unsubscriberForm);
		if (result.equals("success"))
			return NavigationConstant.SUCCESS;
		return NavigationConstant.FAILED;
	}

	@Override
	@RequestMapping(value = "updateSubscribers.htm", method = RequestMethod.POST)
	public String notifySubscribers(UpdateForm updateForm) {
		List<SubscriberForm> subscribers = rssService.getAllSubscribers(ProviderConstant.DAILYSPORTS);
		if(subscribers==null){
			return NavigationConstant.FAILED;
		}
		updateForm.setUpdateFrom(ProviderConstant.DAILYSPORTS);
		updateForm.setCdate(DateUtils.getCurrentDateInSQLFormat());
		String result = rssService.saveUpdate(updateForm);
		System.out.println("Saving update: " + result);
		result = emailSpringService.sendMail(subscribers, updateForm);
		System.out.println("Sending updates: " + result);
		return result;
	}

}
